# coding:utf-8
import os
import re
import time

from lxml.builder import basestring


def make_deal_file(data, condition, var_dick_data):
    template = """
# coding:utf-8


params = {{data}}


store = {{var_dick_data}}

{{condition}}

"""

    if not isinstance(data, basestring):
        data = str(data)
    if not isinstance(var_dick_data, basestring):
        var_dick_data = str(var_dick_data)
    r = template.replace('{{data}}', data).replace('{{condition}}', condition).replace('{{var_dick_data}}',
                                                                                       var_dick_data)
    # 将文件的true替换为True，false替换为False
    replace_true = re.sub('true', 'True', r)
    replace_false = re.sub('false', 'False', replace_true)
    content = replace_false

    tmp_directory = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '/document/tmp/'
    if not os.path.exists(tmp_directory):
        os.makedirs(tmp_directory)
    file_name = 'python_' + str(int(time.time() * 100)) + '.py'
    path = tmp_directory + file_name

    with open(path, 'w', encoding='utf-8') as f:
        f.write(content)
        f.close()

    return path


def remove_deal_file(path):
    if os.path.exists(path):
        os.remove(path)


if __name__ == '__main__':
    try:
        rs = '{"code": 200}'
        fun = "store['code'] = params['code'] \n" \
              "name = params['code'] \n" \
              "assert params['code'] == 300"
        var_dick = '200'
        deal_path = make_deal_file(rs, fun, var_dick)
        result = os.popen('python ' + deal_path)
        result_str = re.sub('\'', '\"', result.read())
        print(result_str)
        remove_deal_file(deal_path)
        # deal_res = json.loads(result_str)
        # print(deal_res)
    # except AssertionError as e:
    #     if 'AssertionError' in e:
    #         print(e)
    #         raise e
    except BaseException as e:
        raise e
